package com.skyline.courier.net.provider.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import com.skyline.courier.net.Heartbeat;
import com.skyline.courier.net.Serializer;

public class NettyDeserializeHandler extends ChannelInboundHandlerAdapter {
	private Serializer serializer;

	public NettyDeserializeHandler(Serializer serializer) {
		this.serializer = serializer;
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		if (msg == null) {
			return;
		} else if (msg instanceof byte[]) {
			byte[] bytes = (byte[]) msg;
			Object oriMsg = null;
			if (bytes.length == 0) {
				oriMsg = Heartbeat.getHeartbeat();
			} else {
				try {
					oriMsg = serializer.deserialize(bytes);
				} catch (Exception ex) {
					throw ex;
				}
			}
			super.channelRead(ctx, oriMsg);
		} else {
			super.channelRead(ctx, msg);
		}

	}
}
